package pool

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/carlmjohnson/requests"
	"xtsec.com/dns-syncer/common"
	"xtsec.com/dns-syncer/common/tools"
)

var uaList = []string{
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
	"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) CriOS/27.0.1453.10 Mobile/10B350 Safari/8536.25",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15",
	"Opera/9.80 (Android 2.3.3; Linux; Opera Mobi/ADR-1111101157; U; es-ES) Presto/2.9.201 Version/11.50",
}

type IPResponse struct {
	Target string
	Ip     string `json:"ip" validate:"ip"`
}

func (ir IPResponse) Value() *IPResponse {
	return &ir
}

type base struct {
	target string
	lookup string
}

func config(target string, rb *requests.Builder) {
	timeout := common.GetRequestTimeout()
	cl := http.Client{Timeout: time.Duration(timeout) * time.Second}
	rb.Client(&cl)
	fmt.Printf("[%s]current client config timeout: %ds\n\n", target, timeout)
}

func (base base) client() *requests.Builder {
	rb := requests.URL(base.lookup)
	config(base.target, rb)
	return rb
}

func (base base) GetIPResponse(ctx context.Context) (IPResponse, error) {
	ir := IPResponse{Target: base.target}

	err := base.client().ToJSON(&ir).Fetch(ctx)
	if err != nil {
		return ir, err
	}

	if err := tools.ValidateStruct(ir); err != nil {
		return ir, err
	}

	return ir, nil
}
